<?php
	/**
	 * Created by PhpStorm.
	 * User: yf
	 * Date: 2018/3/6
	 * Time: 下午2:54
	 */

	namespace App\Sock\Controller;


	use App\Utility\Redis;
	use App\Utility\RedisPool;
	use App\Utility\Sum;
	use EasySwoole\Config;
	use EasySwoole\Core\Socket\Response;
	use EasySwoole\Core\Socket\WebSocketController;
	use EasySwoole\Core\Swoole\Coroutine\PoolManager;
	use EasySwoole\Core\Swoole\ServerManager;
	use EasySwoole\Core\Swoole\Task\TaskManager;


	class Web extends WebSocketController
	{
		function actionNotFound(?string $actionName)
		{
			$this->response()->write("action call {$actionName} not found");
		}

		function hello()
		{
			$Redis = Redis::getInstance()->getConnect();
			$fd = $this->client()->getFd();


			$Redis->set('fd_' . $fd, $fd);


			if (!$Redis->get('money')) {
				$Redis->set('money', 1);
			}

			$Redis->set('money', $Redis->get('money') + 1);

			$this->response()->write(json_encode([$Redis->get('money'), $Redis->keys('fd_*')]));


//			$this->response()->write('call hello with arg:'.$this->request()->getArg('content'));
			foreach ($Redis->keys('fd_*') as $item) {

				$this->push($Redis->get($item), $Redis->get('money'));
			}


		}

		function push($fd, $money)
		{
			$info = ServerManager::getInstance()->getServer()->connection_info($fd);
			if (is_array($info)) {
				ServerManager::getInstance()->getServer()->push($fd, '今日股价为：' . $money);
			} else {
				$this->response()->write("fd {$fd} not exist");
			}
		}

		public function who()
		{
			$fd = $this->client()->getFd();
			$this->response()->write('your fd is ' . $fd . ' and detail info is ' . json_encode(ServerManager::getInstance()->getServer()->connection_info($fd)));
		}

		function delay()
		{
			$this->response()->write('this is delay action');
			$client = $this->client();
			//测试异步推送
			TaskManager::async(function() use ($client) {
				sleep(1);
				Response::response($client, 'this is async task res' . time());
			});
		}
	}